/**
 * Created by spatra on 14-9-8.
 */

define(['jquery', 'lib/mathhelper'], function($, MathHelper){
	var mouseDownStatus = false;

	var mouseStartCoordinate = {};
	var theCanvas;

	var run = function (entities) {
		if( !mouseDownStatus ){
			return;
		}

		var startX = mouseStartCoordinate.x, startY = mouseStartCoordinate.y;

		var targetEntity = null;
		var minDistance = Math.pow(10, 4);

		var result = correctCoordinateInCanvas(theCanvas, startX, startY);
		startX = result.x;
		startY = result.y;

		for (var i = 0; i < entities.getLength(); ++i) {

			var distance = MathHelper.resolveDistanceByCoordinate(entities.get(i).x, entities.get(i).y, startX, startY);

			if (entities.get(i).radius >= distance && distance < minDistance) {
				targetEntity = entities.get(i);
				minDistance = distance;
			}
		}

		if (targetEntity !== null) {

			targetEntity.dragStatus = true;
			mouseDownStatus = false;

			var dx = targetEntity.x - startX;
			var dy = targetEntity.y - startY;

			var startTime = ( new Date ).getTime();

			var endX, endY;

			$(theCanvas).on('mousemove', function (event) {
				$(this).css('cursor', 'pointer');
				var coordinate = correctCoordinateInCanvas(theCanvas, event.pageX, event.pageY);
				var currentX = coordinate.x, currentY = coordinate.y;

				targetEntity.x = currentX + dx;
				targetEntity.y = currentY + dy;

				endX = currentX;
				endY = currentY;


			}).on('mouseup', function () {
				targetEntity.dragStatus = false;

				var dragAX = (endX - startX) / theCanvas.width * 10;
				var dragAY = (endY - startY) / theCanvas.height * 10;

				var endTime = (new Date).getTime();
				var draggingTime = 6 * 1000 / (endTime - startTime);


				targetEntity.vx = (targetEntity.vx + dragAX * draggingTime);
				targetEntity.vy = (targetEntity.vy + dragAY * draggingTime);

				$(theCanvas).off('mousemove').css('cursor', '');
				$(theCanvas).off('mouseup');
			});

		}
	};

	var correctCoordinateInCanvas = function (theCanvas, x, y) {
		var $theCanvas = $(theCanvas);

		return{
			x: x - $theCanvas.offset().left,
			y: y - $theCanvas.offset().top
		}
	};

	var inCanvas = function(theCanvas, coordinate){
		var $theCanvas = $(theCanvas);

		var checkTopLeft =
			$theCanvas.offset().left < coordinate.x &&
			$theCanvas.offset().top < coordinate.y;

		var checkBottomRight =
			$theCanvas.offset().left + theCanvas.width > coordinate.x &&
			$theCanvas.offset().top + theCanvas.height > coordinate.y;

		return checkTopLeft && checkBottomRight;

	};

	var mouseDownListener = function(event){
		mouseStartCoordinate.x = event.pageX;
		mouseStartCoordinate.y = event.pageY;

		mouseDownStatus = inCanvas(theCanvas, mouseStartCoordinate);
	};


	return {
		run: run,
		correctCoordinateInCanvas: correctCoordinateInCanvas,
		inCanvas: inCanvas,
		mouseDownListener: mouseDownListener,
		init: function(canvas){
			theCanvas = canvas;
		}
	};

});